from django.db import models
from django.utils import timezone
from apps.users.models import User
from apps.articles.models import Article


class Comment(models.Model):
    """评论模型"""
    comment_id = models.AutoField(primary_key=True, verbose_name='Comment ID')
    p_comment_id = models.IntegerField(default=0, verbose_name='Parent Comment ID')
    article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments', verbose_name='Article')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Comment User')
    reply_user_id = models.IntegerField(blank=True, null=True, verbose_name='Reply User ID')
    content = models.TextField(verbose_name='Comment Content')
    img_path = models.CharField(max_length=500, blank=True, null=True, verbose_name='Comment Image')
    top_type = models.BooleanField(default=False, verbose_name='Top Type')
    good_count = models.IntegerField(default=0, verbose_name='Like Count')
    post_time = models.DateTimeField(default=timezone.now, verbose_name='Comment Time')
    
    class Meta:
        db_table = 'comments'
        verbose_name = 'Comment'
        verbose_name_plural = 'Comments'
        indexes = [
            models.Index(fields=['p_comment_id']),
            models.Index(fields=['article']),
            models.Index(fields=['user']),
            models.Index(fields=['post_time']),
        ]
        
    def __str__(self):
        return f"{self.user.nickname} - {self.content[:50]}"
    
    @property
    def nick_name(self):
        """动态获取评论用户昵称"""
        return self.user.nickname if self.user else ''
    
    @property
    def reply_nick_name(self):
        """动态获取回复用户昵称"""
        if self.reply_user_id:
            try:
                reply_user = User.objects.get(user_id=self.reply_user_id)
                return reply_user.nickname
            except User.DoesNotExist:
                return ''
        return ''